import { ChatMessage, ChatEvent } from './types';
import { Entity } from '@/entities/Entity';

export class ChatUI {
    private container!: HTMLElement;
    private chatPanel!: HTMLElement;
    private messagesContainer!: HTMLElement;
    private inputContainer!: HTMLElement;
    private messageInput!: HTMLInputElement;
    private sendButton!: HTMLElement;
    private targetInfo!: HTMLElement;
    private typingIndicator!: HTMLElement;
    private isVisible = false;
    private onMessageSendCallback?: (message: string) => void;

    constructor() {
        this.createUI();
        this.setupEventListeners();
    }

    private createUI(): void {
        // 创建主容器
        this.container = document.createElement('div');
        this.container.id = 'chat-container';
        this.container.className = 'chat-container hidden';
        
        // 创建聊天面板
        this.chatPanel = document.createElement('div');
        this.chatPanel.className = 'chat-panel';
        
        // 创建目标信息显示
        this.targetInfo = document.createElement('div');
        this.targetInfo.className = 'chat-target-info';
        this.targetInfo.textContent = '选择一个生物开始对话...';
        
        // 创建消息容器
        this.messagesContainer = document.createElement('div');
        this.messagesContainer.className = 'chat-messages';
        
        // 创建打字指示器
        this.typingIndicator = document.createElement('div');
        this.typingIndicator.className = 'typing-indicator hidden';
        this.typingIndicator.innerHTML = '<span>生物正在思考</span><div class="typing-dots"><span></span><span></span><span></span></div>';
        
        // 创建输入容器
        this.inputContainer = document.createElement('div');
        this.inputContainer.className = 'chat-input-container';
        
        // 创建输入框
        this.messageInput = document.createElement('input');
        this.messageInput.type = 'text';
        this.messageInput.className = 'chat-input';
        this.messageInput.placeholder = '输入消息...';
        this.messageInput.maxLength = 256;
        
        // 创建发送按钮
        this.sendButton = document.createElement('button');
        this.sendButton.className = 'chat-send-button';
        this.sendButton.textContent = '发送';
        
        // 组装UI
        this.inputContainer.appendChild(this.messageInput);
        this.inputContainer.appendChild(this.sendButton);
        
        this.chatPanel.appendChild(this.targetInfo);
        this.chatPanel.appendChild(this.messagesContainer);
        this.chatPanel.appendChild(this.typingIndicator);
        this.chatPanel.appendChild(this.inputContainer);
        
        this.container.appendChild(this.chatPanel);
        
        // 添加到页面
        document.body.appendChild(this.container);
        
        // 添加CSS样式
        this.addStyles();
    }

    private addStyles(): void {
        const style = document.createElement('style');
        style.textContent = `
            .chat-container {
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                z-index: 1000;
                pointer-events: none;
            }
            
            .chat-container.hidden {
                display: none;
            }
            
            .chat-panel {
                width: 400px;
                height: 300px;
                background: rgba(0, 0, 0, 0.8);
                border: 2px solid #666;
                border-radius: 8px;
                display: flex;
                flex-direction: column;
                pointer-events: auto;
                font-family: 'Courier New', monospace;
                color: white;
            }
            
            .chat-target-info {
                padding: 8px 12px;
                background: rgba(255, 255, 255, 0.1);
                border-bottom: 1px solid #666;
                font-size: 12px;
                color: #ccc;
                text-align: center;
            }
            
            .chat-messages {
                flex: 1;
                overflow-y: auto;
                padding: 8px;
                display: flex;
                flex-direction: column;
                gap: 4px;
            }
            
            .chat-message {
                padding: 4px 8px;
                border-radius: 4px;
                max-width: 80%;
                word-wrap: break-word;
                font-size: 13px;
                line-height: 1.4;
            }
            
            .chat-message.player {
                background: rgba(0, 100, 200, 0.3);
                align-self: flex-end;
                text-align: right;
            }
            
            .chat-message.entity {
                background: rgba(100, 200, 0, 0.3);
                align-self: flex-start;
            }
            
            .chat-message-sender {
                font-size: 11px;
                opacity: 0.7;
                margin-bottom: 2px;
            }
            
            .typing-indicator {
                padding: 8px;
                text-align: center;
                font-size: 12px;
                color: #aaa;
            }
            
            .typing-indicator.hidden {
                display: none;
            }
            
            .typing-dots {
                display: inline-block;
                margin-left: 8px;
            }
            
            .typing-dots span {
                display: inline-block;
                width: 4px;
                height: 4px;
                border-radius: 50%;
                background: #aaa;
                margin: 0 1px;
                animation: typing 1.4s infinite ease-in-out;
            }
            
            .typing-dots span:nth-child(1) { animation-delay: -0.32s; }
            .typing-dots span:nth-child(2) { animation-delay: -0.16s; }
            
            @keyframes typing {
                0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
                40% { transform: scale(1); opacity: 1; }
            }
            
            .chat-input-container {
                display: flex;
                padding: 8px;
                border-top: 1px solid #666;
                gap: 8px;
            }
            
            .chat-input {
                flex: 1;
                padding: 6px 8px;
                background: rgba(255, 255, 255, 0.1);
                border: 1px solid #666;
                border-radius: 4px;
                color: white;
                font-family: inherit;
                font-size: 13px;
            }
            
            .chat-input:focus {
                outline: none;
                border-color: #888;
                background: rgba(255, 255, 255, 0.15);
            }
            
            .chat-send-button {
                padding: 6px 12px;
                background: rgba(0, 150, 0, 0.7);
                border: 1px solid #666;
                border-radius: 4px;
                color: white;
                font-family: inherit;
                font-size: 13px;
                cursor: pointer;
                transition: background 0.2s;
            }
            
            .chat-send-button:hover {
                background: rgba(0, 180, 0, 0.8);
            }
            
            .chat-send-button:disabled {
                background: rgba(100, 100, 100, 0.5);
                cursor: not-allowed;
            }
            
            /* 滚动条样式 */
            .chat-messages::-webkit-scrollbar {
                width: 6px;
            }
            
            .chat-messages::-webkit-scrollbar-track {
                background: rgba(255, 255, 255, 0.1);
            }
            
            .chat-messages::-webkit-scrollbar-thumb {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 3px;
            }
            
            .chat-messages::-webkit-scrollbar-thumb:hover {
                background: rgba(255, 255, 255, 0.5);
            }
        `;
        document.head.appendChild(style);
    }

    private setupEventListeners(): void {
        // 发送按钮点击
        this.sendButton.addEventListener('click', () => {
            this.sendMessage();
        });
        
        // Note: Enter key handling is now managed by EnhancedInputHandler
        // We still keep this for fallback, but prevent default to avoid conflicts
        this.messageInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                // Let EnhancedInputHandler handle this
                return;
            }
        });
        
        // 阻止输入时的游戏控制
        this.messageInput.addEventListener('focus', () => {
            // 通知游戏暂停输入处理
            document.dispatchEvent(new CustomEvent('chatInputFocus'));
        });
        
        this.messageInput.addEventListener('blur', () => {
            // 通知游戏恢复输入处理
            document.dispatchEvent(new CustomEvent('chatInputBlur'));
        });
    }

    private sendMessage(): void {
        const message = this.messageInput.value.trim();
        if (!message || !this.onMessageSendCallback) {
            return;
        }
        
        this.messageInput.value = '';
        this.onMessageSendCallback(message);
    }

    public sendCurrentMessage(): void {
        this.sendMessage();
    }

    public show(): void {
        this.isVisible = true;
        this.container.classList.remove('hidden');
        this.messageInput.focus();
    }

    public hide(): void {
        this.isVisible = false;
        this.container.classList.add('hidden');
        this.messageInput.blur();
    }

    public toggle(): void {
        if (this.isVisible) {
            this.hide();
        } else {
            this.show();
        }
    }

    public addMessage(message: ChatMessage): void {
        const messageElement = document.createElement('div');
        messageElement.className = `chat-message ${message.sender}`;
        
        const senderElement = document.createElement('div');
        senderElement.className = 'chat-message-sender';
        senderElement.textContent = message.sender === 'player' ? '你' : (message.entityType || '生物');
        
        const contentElement = document.createElement('div');
        contentElement.textContent = message.content;
        
        messageElement.appendChild(senderElement);
        messageElement.appendChild(contentElement);
        
        this.messagesContainer.appendChild(messageElement);
        
        // 滚动到底部
        this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
        
        // 限制UI中显示的消息数量（存储中的消息由ChatStorage管理）
        const messages = this.messagesContainer.children;
        if (messages.length > 50) {
            this.messagesContainer.removeChild(messages[0]);
        }
    }

    public loadHistoryMessages(messages: ChatMessage[]): void {
        // 清空现有消息
        this.messagesContainer.innerHTML = '';
        
        // 添加历史消息
        messages.forEach(message => {
            this.addMessage(message);
        });
        
        // 滚动到底部
        this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
    }

    public showTypingIndicator(): void {
        this.typingIndicator.classList.remove('hidden');
    }

    public hideTypingIndicator(): void {
        this.typingIndicator.classList.add('hidden');
    }

    public updateTargetInfo(entity: Entity | null): void {
        if (entity) {
            const entityType = entity.getType();
            const distance = Math.floor(entity.getDistanceTo({ x: 0, y: 0, z: 0 })); // 简化距离计算
            this.targetInfo.textContent = `正在与 ${entityType} 对话 (距离: ${distance}m)`;
        } else {
            this.targetInfo.textContent = '选择一个生物开始对话...';
        }
    }

    public clearMessages(): void {
        this.messagesContainer.innerHTML = '';
    }

    public onMessageSend(callback: (message: string) => void): void {
        this.onMessageSendCallback = callback;
    }

    public setInputEnabled(enabled: boolean): void {
        this.messageInput.disabled = !enabled;
        this.sendButton.classList.toggle('disabled', !enabled);
    }

    public getIsVisible(): boolean {
        return this.isVisible;
    }

    public dispose(): void {
        if (this.container && this.container.parentNode) {
            this.container.parentNode.removeChild(this.container);
        }
    }
}